# 安装  pip install pymysql

import pymysql


def connect2mysql():
    try:
        # 1.获取连接
        connection = pymysql.Connect(
            host='127.0.0.1',
            port=3306,   #  注意这个端口不是str类型的
            db='test',
            user='root',
            passwd='root',
            charset='utf8'
        )
        # 2.创建游标对象
        cursour = connection.cursor()
        # 3.增
        insert_sql = 'insert into stu values (3,"zhangsan_3",21)'
        result = cursour.execute(insert_sql)
        print(result)
        # 4.提交事务
        connection.commit()
        # 5.关闭游标
        cursour.close()
        # 6.关闭连接
        connection.close()
    except Exception as e:
        print(e)


def updat2mysql():
    try:
        # 1.获取连接
        connection = pymysql.Connect(
            host='127.0.0.1',
            port=3306,   #  注意这个端口不是str类型的
            db='test',
            user='root',
            passwd='root',
            charset='utf8'
        )
        # 2.创建游标对象
        cursour = connection.cursor()
        # 3.增
        update_sql = 'update stu set age=22 where id=2'
        result = cursour.execute(update_sql)
        print(result)
        # 4.提交事务
        connection.commit()
        # 5.关闭游标
        cursour.close()
        # 6.关闭连接
        connection.close()
    except Exception as e:
        print(e)


def del2mysql():
    try:
        # 1.获取连接
        connection = pymysql.Connect(
            host='127.0.0.1',
            port=3306,   #  注意这个端口不是str类型的
            db='test',
            user='root',
            passwd='root',
            charset='utf8'
        )
        # 2.创建游标对象
        cursour = connection.cursor()
        # 3.增
        del_sql = 'delete from stu where id=2'
        result = cursour.execute(del_sql)
        print(result)
        # 4.提交事务
        connection.commit()
        # 5.关闭游标
        cursour.close()
        # 6.关闭连接
        connection.close()
    except Exception as e:
        print(e)


def find2mysql():
    try:
        # 1.获取连接
        connection = pymysql.Connect(
            host='127.0.0.1',
            port=3306,   #  注意这个端口不是str类型的
            db='test',
            user='root',
            passwd='root',
            charset='utf8'
        )
        # 2.创建游标对象
        cursour = connection.cursor()
        # 3.增
        select_sql = 'select * from stu'
        cursour.execute(select_sql)
        results = cursour.fetchall()
        for ret in results:
            print(ret)
        # 4.提交事务
        connection.commit()
        # 5.关闭游标
        cursour.close()
        # 6.关闭连接
        connection.close()
    except Exception as e:
        print(e)


find2mysql()
